const express = require('express');
const expressWs = require('express-ws');
const drawCaptcha = require('./captcha');
const path = require("path");

const app = express();
expressWs(app)

app.use("/static", express.static("static"))

app.get("/", (req, res) => {
  res.sendFile(path.join(__dirname, "./views/demo.html"));
});

app.ws("/test", (ws, req, next) => {
  let raIndex = Math.floor(Math.random() * 9)
  let raMatchIndex = Math.floor(Math.random() * 4)
  let { img, block, match, matchBorder } = drawCaptcha(raIndex, raMatchIndex)
  ws.on("message", res => {
    let info = JSON.parse(res);
    if (info.Step == 0) {
      new Promise((resolve, reject) => {
        img.toBuffer((e, buf) => {
          if (e) reject(e);
          ws.send(buf);
          resolve();
        });
      }).then(_ => {
        return new Promise((resolve, reject) => {
          block.toBuffer((e, buf) => {
            if (e) reject(e);
            ws.send(buf);
            resolve();
          });
        })
      }).then(_ => {
        return new Promise((resolve, reject) => {
          match.toBuffer((e, buf) => {
            if (e) reject(e);
            ws.send(buf);
            resolve()
          });
        })
      }).then(_ => {
        matchBorder.toBuffer((e, buf) => {
          if (e) reject(e);
          ws.send(buf);
        });
      }).catch(err => {
        console.log(err);
        ws.close();
      });
    } else if (info.Step == 1) {
      ws.send(JSON.stringify({ Step: 0, index: (raIndex - raIndex % 3) / 3 }));
    } else if (info.Step == 2) {
      ws.send(JSON.stringify({ Step: 1, isSuccessful: Math.abs(info.position - 1 - raIndex % 3) < 0.1 }));
      ws.close();
    }
  })
})

app.listen(4000, () => {
  console.log(`App listening at http://localhost:4000`);
})